package com.ailink.app;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/11/27
 */
@RestController
public class LockController {

    @RequestMapping("/test/lock1")
    public String testLock1() {
        RedissonClient client = getRedissonClient();

        RLock lock1 = client.getLock("redis:lock");
        lock1.lock(60, TimeUnit.SECONDS);

        return "/test/lock1";
    }

    @RequestMapping("/test/lock2")
    public String testLock2() {
        RedissonClient client = getRedissonClient();

        RLock lock = client.getLock("redis:lock");
        boolean success = lock.tryLock();
        if (success) {
            return "success";
        } else {
            return "failure";
        }
    }

    private RedissonClient getRedissonClient() {
        Config config = new Config();
        config.useSingleServer()
                .setTimeout(1000000)
                .setAddress("redis://192.168.238.133:6379");
        return Redisson.create(config);
    }
}
